
var http = require('../../../../service/http.js');//请求类
var util = require('../../../../utils/util.js');//工具类

const app = getApp();
var rd_session  = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: '省份      城市      区县',//['省份 ', '城市 ', ' 区县'],  //初始化地区显示
    customItem: '',
    //--------------验证表单------------------
    phoneNum:'',
    isPhone:'',//是否为手机号

    //--------------调用微信接口添加地址-----------
    isFromWX: false,//是否选择了微信地址
    userName: '',//用户名
    telNumber: '',//手机号
    regionInfo: '',//地区信息
    detailInfo: '',//详细地址

    addressObj:{},//地址对象
    hasAddress:false,//是否有默认地址
    isEdit:false,//是否是编辑状态
    addressList:[],//地址列表
    aid:0,//编辑地址id
    isAdd: false,//是否是新增

    //------------表单验证提示信息----------------
    msg:'',
    //------------授权弹出层----------------------
    showSettingBox: false,//打开引导用户设置弹出层
    authorizeMsg: '',//授权信息提示
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //请求收货地址列表
    let that = this;
    rd_session = wx.getStorageSync('rd_session');
    let defaultAddress = wx.getStorageSync('defaultAddress');
    console.log(defaultAddress);
    if (defaultAddress != '') {
      wx.setNavigationBarTitle({
        title: '选择收获地址'
      })
    } else {
      wx.setNavigationBarTitle({
        title: '新增收货地址'
      })
    }
    console.log(that.data.hasAddress);
  },

  onReady:function(){
    //请求收货地址列表
    let that = this;
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: function(res) {

        http.getReq('/weixin/userDeliveredInfo/list', {
          rdSession: rd_session
        }, function (res) {

          console.log(res);

          let addressList = res.data;
          if (res.data.length > 0) {
            that.setData({
              addressList: addressList,
              hasAddress: true
            })
          } else {
            that.setData({
              hasAddress: false
            })
          }
          wx.hideLoading();
        });
       
      }
    })
 
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  chooseAddress: function () {//选择微信地址
    console.log('选择微信收货地址');
    let that = this;
    let hasAddress = that.data.hasAddress;
    let regionInfo = '';//地区信息
    let [userName, telNumber, provinceName, cityName, countyName, detailInfo] = ['','','','','',''];
    wx.chooseAddress({
      success: function(res) {
        console.log(res);
        let errMsg = res.errMsg;//是否选择了地址 chooseAddress:ok
        if (errMsg == 'chooseAddress:ok'){//有已经选择的地址
           userName = res.userName;//用户名
           telNumber = res.telNumber;//电话

           provinceName = res.provinceName;//省份；
           cityName = res.cityName;//市；
           countyName = res.countyName;//区；
           detailInfo = res.detailInfo;//详细地址；
           regionInfo = provinceName + ' ' + cityName + ' ' + countyName;//地区信息
           that.setData({
             userName: userName,
             telNumber: telNumber,
             regionInfo: regionInfo,
             detailInfo: detailInfo,
             isFromWX:true,
           })
           //选择后直接提交订单
           that.saveAddress();
        }
      },
      fail: function(res) {
        console.log('获取微信地址失败');
        console.log(res)
        let errMsg = res.errMsg;
        if (errMsg == 'chooseAddress:fail auth deny'){
          that.showSettingBox();
        }
      },
     
    })
  },

  //保存地址
  saveAddress:function(e){
    console.log(e);
    console.log("保存地址");
    if(e){//获取formid
      this.getFormId(e);
    }
    let that = this;
    that.setData({
      msg: ''
    })
    
    let regionInfo = that.data.regionInfo;//地区信息
    let addressObj = {};//用于传递后台的参数对象
    let [userName,  provinceName, cityName, countyName] = ['', '', '', ''];
    let [name, postalCode, pcc, detailInfo, telNumber,msg,id] = ['','','','','','',''];
    let requestUrl = '/weixin/userDeliveredInfo/add';//请求地址
   // let method = ''
    if(e){//提交表单保存地址
      console.log(e);
  
     // method = "add";
      name = e.detail.value.userName;//姓名
      if (e.detail.value.aid != 0 ){//编辑地址
        id = e.detail.value.aid;//编辑地址的id
        requestUrl = '/weixin/userDeliveredInfo/update'
      }
      postalCode = '';
      console.log(e.detail.value.region);
      if (e.detail.value.region.length > 0 ){
        pcc = e.detail.value.region.toString();//省市区
        console.log(pcc);
        let  pccArr = pcc.split(',');
        pcc = pccArr[0] + ' ' + pccArr[1] + ' '+pccArr[2];
      }else{
        pcc = '';
      }
      detailInfo = e.detail.value.detailInfo;//详细地址
      telNumber = e.detail.value.telNumber;//收货人手机号
      
      //------------填写验证信息------------------------
      if (name == ''){
        msg = '请输入收货人姓名';
      } else if (!(/^1[34578]\d{9}$/.test(telNumber))) {
        console.log(telNumber);
        msg = '请输入正确的手机号';
      }else if (!pcc){
        console.log(pcc);
        msg = '请选择地区信息';
      }else if (detailInfo == '') {
        msg = '请输入收货人详细地址';
      } 
    }else{//通过微信接口选择提交保存地址
      name = that.data.userName;//姓名
      postalCode = '';
      pcc = regionInfo//省市区
      detailInfo = that.data.detailInfo;//详细地址
      telNumber = that.data.telNumber;//收货人手机号
    }
    //消息提示
    if (msg !== ''){//校验失败
      that.setData({
        msg: msg
      })
      return 
    }else{//保存地址信息
      addressObj.name = name;
      addressObj.postalCode = postalCode;
      addressObj.pcc = pcc;
      addressObj.detailInfo = detailInfo;
      addressObj.telNumber = telNumber;
      addressObj.id = id;
      http.getReq(requestUrl, {
        rdSession: rd_session,
        addressObj: addressObj,
      }, function (res) {
        console.log(res);

        if (res.ret) {
          wx.setStorageSync('defaultAddress', addressObj);

          util.showToast('保存成功', 1000, 'success', function () {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1,
              })
            }, 1000)
          });
         
        }
      });
    
    }
  },

  selectAddress:function(e){//选择地址.将选择的地址设置未默认
    console.log(e);
    let that = this;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    console.log('id=' + id);
    // 修改订单地址状态

    http.getReq('/weixin/userDeliveredInfo/selectDefault', {
      rdSession: rd_session,
      id: id
    }, function (res) {
      if (res.ret) {
        let addressList = that.addressList;//选择的地址
        console.log(addressList);
        wx.setStorageSync('defaultAddress', addressList[index]);//默认收获地址用于订单详情页显示
        //返回待付款订单页
        wx.navigateBack({
          delta: 1,
        })
      }
    });
  },

  editAddress:function(e){//编辑商品地址
    wx.setTopBarText({
      text: '编辑收货地址'
    })
    console.log(e);
    let that = this;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;//地址id
    let addressList = that.data.addressList;//选择的地址
    that.setData({
      isEdit:true,
      userName: addressList[index].name,
      region: addressList[index].pcc,
      telNumber: addressList[index].telNumber,
      detailInfo: addressList[index].detailInfo,
      aid: id
    })
  },
  delAddress:function(e){
    console.log("删除地址")
    let id = e.currentTarget.dataset.id;//地址id

    http.getReq('/weixin/userDeliveredInfo/delete', {
      id: id,
      rdSession: rd_session
    }, function (res) {
      if (res.ret) {
        util.showToast('删除成功', 1000, 'success', function () {
          setTimeout(function () {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000)
         });
      }
    });
   
  },
  addAddress:function(e){//新增地址
    console.log('新增地址');
    let that = this;
    that.setData({
      userName:'',
      region: that.data.region,
      telNumber: '',
      detailInfo: '',
      aid: '',
      isAdd:true
    })
  },
  getFormId: function (e) {
    console.log(e);
    app.getFormId(e);
  },
  cancelSettingBox: function () { //关闭设置提示窗
    app.cancelSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox
    })
  },
  showSettingBox: function () {//打开设置提示窗
    app.showSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox,
      authorizeMsg: '访问通讯地址',//授权信息提示
    })
  },

  bindopensetting:function(e){//设置授权（去设置）
    console.log(e)
    let that = this;
    let authSetting = e.detail.authSetting['scope.address'];
    if (authSetting == true) {//同意授权
      //获取微信地址
      that.chooseAddress();
      that.cancelSettingBox();
    }
  }
})